from sys import argv
from sys import stdout

if len(argv) != 4:
	print 'usage: >python parse_repeat refFile repeatFile chromoNum'
	exit(1)

refFileName, repeatFileName = argv[1:3]

chromoNum = int(argv[3])

print "refFile: ", refFileName

print "repeatFile: ", repeatFileName

print "chromoNum: %r" % chromoNum

def gotoChromo(refFile, chromoNum):
	i = 0
	while i != chromoNum:
		while True:
			temp = refFile.readline()
			if temp[0] == '>':
				print temp
				break
		i = i + 1

def loadRefChromo(refFile, chromoNum):
	gotoChromo(refFile, chromoNum)
	chromosome = ""
	while True:
		temp = refFile.readline()
		if len(temp) == 0 or temp[0] == '>':
			print "stop: ", temp
			break
		else:
			temp = temp.rstrip()
			chromosome+=temp
	return chromosome

def loadRepeat(repeatFile):
	repeatString = ""
	while True:
		temp = repeatFile.readline()
		if len(temp) == 0:
			break
		else:
			temp = temp.rstrip()
			repeatString += temp
	return repeatString

refFile = open(refFileName)
repeatFile = open(repeatFileName)

temp = refFile.readline()

print temp

temp = repeatFile.readline()

print temp

chromosome = loadRefChromo(refFile, chromoNum)
repeatString = loadRepeat(repeatFile)

repeatBegin = 0
repeatEnd = 0
repeatDist = {}
repeatInterval = 0
inRepeat = False
chromoLength = 0
i = 0
while i < len(chromosome):
	if repeatString[i] == '0'and inRepeat == True:
		inRepeat = False
		repeatEnd = i
		repeatInterval = repeatEnd - repeatBegin
		if repeatInterval in repeatDist:
			repeatDist[repeatInterval] += 1
		else:
			repeatDist[repeatInterval] = 1
		if repeatInterval > 1000:
			repeatSegment = chromosome[repeatBegin:repeatEnd]
			print "Long repeat: ", repeatSegment
			print "repeatBegin: ", repeatBegin
			print "repeatInterval: ", repeatInterval
	elif repeatString[i] =='1' and inRepeat == False:
		repeatBegin = i
		inRepeat = True
	if chromosome[i] != 'N':
		chromoLength += 1
	i+=1

repeatAmount = 0
for i in sorted(repeatDist):
	print i, repeatDist[i]
	repeatAmount += i * repeatDist[i]

print "chromoLength: ", chromoLength
print "repeatAmount: ", repeatAmount


#lineLength = 60
#while (i < len(chromosome) ):
#	if repeatString[i] == '0':
#		stdout.write('0')
#	else:
#		stdout.write(chromosome[i])
#	if i % lineLength == lineLength - 1:
#		stdout.write('\n')
#	i+=1
#
